package com.qiguliuxing.dts.db.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiguliuxing.dts.db.dao.DtsCollectMapper;
import com.qiguliuxing.dts.db.domain.DtsCollect;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DtsCollectService {
	@Resource
	private DtsCollectMapper collectMapper;

	public int count(int uid, Integer gid) {
		QueryWrapper<DtsCollect> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsCollect::getUserId, uid);
		queryWrapper.eq("valueId", gid);
		queryWrapper.eq("deleted", false);
		return collectMapper.selectCount(queryWrapper).intValue();
	}

	public List<DtsCollect> queryByType(Integer userId, Byte type, Integer page, Integer size) {
		QueryWrapper<DtsCollect> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsCollect::getUserId, userId);
		queryWrapper.eq("type", type);
		queryWrapper.eq("deleted", false);
		queryWrapper.orderByDesc("add_time");
		IPage<DtsCollect> iPage = new Page<>(page, size);
		iPage = collectMapper.selectPage(iPage, queryWrapper);
		return iPage.getRecords();
	}

	public int countByType(Integer userId, Byte type) {
		QueryWrapper<DtsCollect> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsCollect::getUserId, userId);
		queryWrapper.eq("type", type);
		queryWrapper.eq("deleted", false);
		return collectMapper.selectCount(queryWrapper).intValue();
	}

	public DtsCollect queryByTypeAndValue(Integer userId, Byte type, Integer valueId) {
		QueryWrapper<DtsCollect> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsCollect::getUserId, userId);
		queryWrapper.eq("type", type);
		queryWrapper.lambda().eq(DtsCollect::getValueId, valueId);
		queryWrapper.eq("deleted", false);
		return collectMapper.selectOne(queryWrapper);
	}

	public void deleteById(Integer id) {
		collectMapper.deleteById(id);
	}

	public int add(DtsCollect collect) {
		collect.setAddTime(LocalDateTime.now());
		collect.setUpdateTime(LocalDateTime.now());
		return collectMapper.insert(collect);
	}

	public List<DtsCollect> querySelective(String userId, String valueId, Integer page, Integer size, String sort,
			String order) {
		QueryWrapper<DtsCollect> queryWrapper = new QueryWrapper<>();
		if (StrUtil.isNotEmpty(userId)) {
			queryWrapper.lambda().eq(DtsCollect::getUserId, userId);
		}
		if (StrUtil.isNotEmpty(valueId)) {
			queryWrapper.lambda().eq(DtsCollect::getValueId, valueId);
		}
		queryWrapper.eq("deleted", false);
		if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)) {
			queryWrapper.orderByDesc(sort);
		}
		IPage<DtsCollect> iPage = new Page<>(page, size);
		iPage = collectMapper.selectPage(iPage, queryWrapper);
		return iPage.getRecords();
	}
}
